package com.robusta.app.persistence;

import com.robusta.app.domain.spreadsheet.templates.Metadata;
import com.robusta.app.model.spreadsheet.templates.PersistableMetadata;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.List;

@Repository
public class WorkbookMetadataRepository {
    @PersistenceContext(unitName = "spreadsheet-model-persistence")
    private EntityManager entityManager;
    private static final Logger LOGGER = LoggerFactory.getLogger(SpreadsheetModelRepository.class);

    public List<? extends Metadata> findAll() {
        List<PersistableMetadata> resultList = entityManager.createQuery(
                "SELECT metadata FROM PersistableMetadata metadata", PersistableMetadata.class)
                .getResultList();
        if(LOGGER.isDebugEnabled()) {
            LOGGER.debug(String.format("Loaded available workbook metadata: %s from the repository", resultList));
        }
        return resultList;
    }

    public Metadata findByName(String name) {
        if(LOGGER.isDebugEnabled()) {
            LOGGER.debug(String.format("Loading workbook metadata from the repository with name: %s", name));
        }
        PersistableMetadata result = entityManager.createQuery(
                "SELECT metadata FROM PersistableMetadata metadata where metadata.name = :name", PersistableMetadata.class)
                .setParameter("name", name).getSingleResult();
        if(LOGGER.isDebugEnabled()) {
            LOGGER.debug(String.format("Loaded workbook metadata: %s from the repository for name: %s", result, name));
        }

        return result;
    }
}
